<template>
  <div class="page-miH page-bgBack">
    <TableTitle>
      <template slot="title">员工详情</template>
      <template slot="action">
        <div style="display: flex; align-items: center">
          <a-badge :count="allCount" :offset="[-18, 0]">
            <a-button type="primary" :style="allCount ? 'margin-right:18px;' : 'margin-right:12px;'" @click="onTodayAdd">今日新增</a-button>
          </a-badge>
          <a-upload ref="upload" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload" class="mr12">
            <a-button type="primary" block>导入</a-button>
          </a-upload>
          <a-button type="primary" @click="download2" class="mr12">下载导入模板</a-button>
          <a-button type="primary" @click="showAdd"> <a-icon type="plus" />添加预登记人员 </a-button>
        </div>
      </template>
    </TableTitle>
    <div class="body">
      <div class="tableBox">
        <TableBody
          selectHead
          tableName="prePersonnel"
          :source="dataList"
          :headerRowID="'sortable_list'"
          :columns="columns"
          :isJF="isJF"
          @onReload="getPrePersonnelList"
          @onExportAll="exportFile"
        >
          <template slot="search">
            <a-input-search allow-clear placeholder="搜索姓名/手机号/身份证号" style="width: 225px" @search="inputChange" />
            <a-select
              allowClear
              show-search
              option-filter-prop="children"
              :filter-option="filterOption3"
              placeholder="请选择渠道"
              @change="selectCheck"
              style="width: 225px"
            >
              <a-select-option v-model="item.id" v-for="(item, index) in Channels" :key="index">{{ item.name }}</a-select-option>
            </a-select>
            <a-select allowClear placeholder="请选择人员状态" @change="selectCheck2" style="width: 225px">
              <a-select-option v-for="li in preStatusVarList" :key="li.value" :value="li.value">{{ li.label }}</a-select-option>
            </a-select>
          </template>
          <template slot="action-btn">
            <a-select style="width: 150px" v-model="batchVal" @change="batchHandleChange">
              <a-select-option value="状态">批量修改状态</a-select-option>
              <a-select-option value="渠道">批量修改渠道</a-select-option>
            </a-select>
          </template>
          <template slot-scope="prop">
            <a-table
              :class="prop.className"
              :components="prop.components"
              :columns="prop.columns"
              :scroll="{ x: prop.scrollWidth }"
              :customHeaderRow="
                () => {
                  return {
                    domProps: {
                      id: prop.headerRowID
                    }
                  };
                }
              "
              :loading="loading"
              rowKey="id"
              :data-source="dataList"
              :pagination="pagination"
              @change="handleTableChange"
            >
              <a slot="status" slot-scope="text" style="cursor: text">
                <div
                  v-if="text === 2"
                  class="statusStyle"
                  style="background: rgba(255, 166, 0, 0.1); border: 1px solid #ffa600; color: #ffa600"
                >
                  已安排
                </div>
                <div
                  v-if="text === 1"
                  class="statusStyle"
                  style="background: rgba(106, 102, 246, 0.1); border: 1px solid #6a66f6; color: #6a66f6"
                >
                  已接到
                </div>
                <div
                  v-if="text === 3"
                  class="statusStyle"
                  style="background: rgba(36, 205, 170, 0.1); border: 1px solid #24cdaa; color: #24cdaa"
                >
                  已面试
                </div>
                <div
                  v-if="text === 4"
                  class="statusStyle"
                  style="background: rgba(66, 130, 255, 0.1); border: 1px solid #4282ff; color: #4282ff"
                >
                  已入职
                </div>
                <div
                  v-if="text === 5"
                  class="statusStyle"
                  style="background: rgba(0, 0, 0, 0.04); border: 1px solid rgba(0, 0, 0, 0.15); color: #767885"
                >
                  已离职
                </div>
                <div
                  v-if="text === 6"
                  class="statusStyle"
                  style="background: rgba(255, 166, 0, 0.1); border: 1px solid #ffa600; color: #ffa600"
                >
                  待入职
                </div>
                <div
                  v-if="text === 7"
                  class="statusStyle"
                  style="background: rgba(0, 0, 0, 0.04); border: 1px solid rgba(0, 0, 0, 0.15); color: #767885"
                >
                  未到岗
                </div>
              </a>
              <a slot="channelName" slot-scope="text" style="cursor: text; color: #595959">{{ text === undefined ? "" : text }}</a>
              <span slot="gmtCreate" slot-scope="text">{{ moment(text).format("YYYY-MM-DD HH:mm") }}</span>
              <span slot="postType" slot-scope="text">{{ $store.state.enums.postTypeArr[text - 1] }}</span>
              <span slot="joinDate" slot-scope="text">{{ text != null ? moment(text).format("YYYY-MM-DD") : "" }}</span>
              <span slot="birthday" slot-scope="text">
                {{ text != null ? `${text.substring(0, 10)}` : "" }}
              </span>
              <span slot="formalType" slot-scope="text">
                <span v-if="text == 1">试用</span>
                <span v-if="text == 2">正式</span>
                <!-- <span v-if="text == 3">实习</span> -->
              </span>
              <a slot="action" class="primary_color" slot-scope="text, record">
                <a-popconfirm
                  title="请选择"
                  :disabled="[4, 6, 7].includes(record.status)"
                  placement="bottom"
                  ok-text="入职"
                  cancel-text="待入职"
                  @cancel="induction(record, 'toBehired')"
                  @confirm="induction(record, 'induction')"
                >
                  <a-button type="link" size="small" :disabled="[4, 6, 7].includes(record.status)">入职</a-button>
                </a-popconfirm>
                <a-divider type="vertical" />
                <a-button type="link" size="small" @click="edit(record)">
                  {{ [4, 6, 7].includes(record.status) ? "查看" : "编辑" }}
                </a-button>
              </a>
            </a-table>
          </template>
        </TableBody>
      </div>
      <div class="drawerBox">
        <a-drawer
          :title="title"
          placement="right"
          :closable="false"
          :visible="visible"
          :destroyOnClose="true"
          @close="onClose"
          :width="580"
        >
          <a-tabs type="card" @change="callback">
            <a-tab-pane key="1" tab="手动添加">
              <div style="display: flex; align-items: center; background: #0000000d; height: 40px; margin-bottom: 20px">
                <div class="emp-title">员工信息</div>
              </div>
              <DynamicAddEmployees
                @saveValueChange="saveValueChange"
                @onRemove="onRemove"
                @cancelForm="cancelForm"
                :title="title"
                :checkInAllValue="checkInAllValue"
                :checkInIdForm="checkInIdForm"
                :moduleCode="'checkIn'"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="机器识别" v-if="form.status !== 4">
              <a-spin :spinning="spinning">
                <a-row type="flex" justify="space-between" style="margin-bottom: 15px">
                  <div style="display: flex; align-items: center">
                    <img v-if="isConnect" style="width: 20px; height: 20px; margin-right: 5px" src="@/assets/icons/duihao.png" />
                    <img v-else style="width: 20px; height: 20px; margin-right: 5px" src="@/assets/icons/失败.png" />
                    <div style="margin-right: 15px">{{ isConnect ? "设备已连接" : "设备未连接" }}</div>
                    <a-button v-if="!isConnect" type="primary" html-type="submit" @click="connectDevice">连接设备</a-button>
                    <a-button v-else html-type="submit" @click="connectDevice">断开设备</a-button>
                    <a-icon type="question-circle" style="margin-left: 10px" @click="howShow" />
                  </div>
                  <a-button :disabled="!isConnect" type="primary" html-type="submit" @click="readIdCard">读卡</a-button>
                </a-row>
                <div style="display: flex; align-items: center; background: #0000000d; height: 40px; margin-bottom: 20px">
                  <div class="emp-title">员工信息</div>
                </div>
                <a-form-model ref="ruleForm" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-form-model-item
                    ref="name"
                    label="姓名"
                    prop="name"
                    :rules="{
                      required: true,
                      message: '请输入员工姓名'
                    }"
                  >
                    <a-input v-model="form.name" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item
                    ref="idcard"
                    label="身份证号"
                    prop="idcard"
                    :rules="{
                      required: true,
                      validator: validatorIdCard
                    }"
                  >
                    <a-input v-model="form.idcard" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item
                    ref="phone"
                    label="手机号码"
                    prop="phone"
                    :rules="{
                      validator: validatorPhone
                    }"
                  >
                    <a-input v-model="form.phone" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="channelId" label="渠道来源" prop="name">
                    <a-select
                      :disabled="form.status === 4"
                      allowClear
                      show-search
                      option-filter-prop="children"
                      :filter-option="filterOption2"
                      placeholder="请选择"
                      @change="selectChange"
                      v-model="form.channelId"
                    >
                      <a-select-option v-model="item.id" v-for="(item, index) in Channels" :key="index">{{ item.name }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item ref="status" label="人员状态" prop="status">
                    <span v-if="form.status === 4">已入职</span>
                    <span v-else-if="form.status === 5">已离职</span>
                    <a-select v-else placeholder="请选择" v-model="form.status">
                      <a-select-option :value="2">已安排</a-select-option>
                      <a-select-option :value="1">已接到</a-select-option>
                      <a-select-option :value="3">已面试</a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item ref="remark" label="备注" prop="remark">
                    <a-textarea v-model="form.remark" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                </a-form-model>

                <div style="display: flex; align-items: center; background: #0000000d; height: 40px; margin-bottom: 20px">
                  <div class="emp-title">身份信息</div>
                </div>

                <a-form-model ref="ruleForm" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
                  <a-form-model-item ref="nation" label="民族" prop="nation">
                    <a-input v-model="form.nation" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="birthday" label="出生日期" prop="birthday">
                    <a-input v-model="form.birthday" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="nativeLocation" label="户籍住址" prop="nativeLocation">
                    <a-input v-model="form.nativeLocation" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="issuedBy" label="签发机关" prop="issuedBy">
                    <a-input v-model="form.issuedBy" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="startDate" label="开始时间" prop="startDate">
                    <a-input v-model="form.startDate" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-model-item ref="endDate" label="结束时间" prop="endDate">
                    <a-input v-model="form.endDate" placeholder="请输入" :disabled="form.status === 4" />
                  </a-form-model-item>
                  <a-form-item label="身份证照片">
                    <img v-if="form.img" style="width: 124px; height: 150px; margin-bottom: 25px" :src="form.img" />
                    <Uploading v-else :srcData.sync="url" :limit="1"></Uploading>
                  </a-form-item>
                </a-form-model>
              </a-spin>
            </a-tab-pane>
          </a-tabs>
          <div class="drawer-footer-box" v-if="key !== '1'">
            <a-button v-if="title === '编辑'" style="margin-right: 12px; color: #fa5051; border-color: #fa5051" @click="showDelete"
              >删除</a-button
            >
            <a-button :style="{ marginRight: '12px' }" @click="onClose">取消</a-button>
            <a-button type="primary" html-type="submit" @click="handleAddOK">确定</a-button>
          </div>
        </a-drawer>
      </div>
      <a-modal title="删除预登记人员" :visible="deleteVisible" @ok="deleteOk" @cancel="deleteCancel">
        <div style="display: flex; justify-content: center">
          <a-icon type="question-circle" style="font-size: 28px; color: #6a66f6" />
          <p style="font-size: 16px; font-weight: 500; color: #3c3d43; line-height: 20px; margin-left: 20px">
            您确定要删除该预登记人员吗？一旦删除不可恢复
          </p>
        </div>
      </a-modal>
      <a-modal
        :title="`${goInductionUrl === 'induction' ? '' : '待'}入职`"
        :visible="inductionVisible"
        @ok="InductOk"
        @cancel="InductCancel"
      >
        <div class="headerBox">
          <div class="titleName">{{ inductDetail.name }}</div>
          <div
            style="
              text-align: center;
              width: 50px;
              height: 20px;
              background: rgba(255, 166, 0, 0.1);
              border-radius: 2px;
              border: 1px solid #ffa600;
              font-size: 11px;
              font-weight: 400;
              color: #ffa600;
              margin-left: 10px;
            "
            v-if="inductDetail.status === 2"
          >
            已安排
          </div>
          <div
            style="
              text-align: center;
              width: 50px;
              height: 20px;
              background: rgba(106, 102, 246, 0.1);
              border-radius: 2px;
              border: 1px solid #6a66f6;
              font-size: 11px;
              font-weight: 400;
              color: #6a66f6;
              margin-left: 10px;
            "
            v-if="inductDetail.status === 1"
          >
            已接到
          </div>
          <div
            style="
              text-align: center;
              width: 50px;
              height: 20px;
              background: rgba(36, 205, 170, 0.1);
              border-radius: 2px;
              border: 1px solid #24cdaa;
              font-size: 11px;
              font-weight: 400;
              color: #24cdaa;
              margin-left: 10px;
            "
            v-if="inductDetail.status === 3"
          >
            已面试
          </div>
        </div>
        <div class="detailBox">
          <div class="detailTitle">联系电话</div>
          <div class="detailContent">{{ inductDetail.phone }}</div>
        </div>
        <div class="detailBox">
          <div class="detailTitle">身份证号</div>
          <div class="detailContent">{{ inductDetail.idcard }}</div>
        </div>
        <div class="detailBox">
          <div class="detailTitle">渠道来源</div>
          <div class="detailContent">{{ inductDetail.channelName }}</div>
        </div>
        <div class="detailBox" style="margin-top: 10px; align-items: center">
          <div class="detailTitle">用工单位</div>
          <div class="detailContent">
            <a-select
              allowClear
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              placeholder="请选择用工单位"
              v-model="storyCompanyId"
              style="width: 215px"
            >
              <a-select-option v-for="item in options" :key="item.id">{{ item.name }}</a-select-option>
            </a-select>
          </div>
        </div>
      </a-modal>
      <a-modal title="使用说明" :visible="isCloseMethod" width="620px" :destroy-on-close="true" :mask-closable="false" @cancel="cancelSyn">
        <template slot="footer">
          <a-button @click="cancelSyn">取消</a-button>
          <a-button type="primary" @click="cancelSyn">确定</a-button>
        </template>
        <div>
          <div style="font-size: 14px; color: #55565d">1、该功能需要外部连接设备读卡器使用</div>
          <div class="rowdalog2">
            <div style="font-size: 14px; color: #55565d">2、需要使用配套驱动和网站。</div>
            <div class="edit" style="font-size: 14px; margin-left: 5px; cursor: pointer" @click="download">驱动及网站链接</div>
          </div>
          <div style="font-size: 14px; color: #55565d">3、设备连接后不会因为页面关闭而主动断开，除非外部连接断开或主动选择设备断开</div>
          <div style="font-size: 14px; color: #55565d">4、每次读取身份证信息需要点击“读卡”</div>
        </div>
      </a-modal>
      <bulkChanges ref="select" @saveOk="saveOk"></bulkChanges>
    </div>
  </div>
</template>
<script>
import { preStatusVarList, columns } from "./funcs";
import {
  getPrePersonnel,
  getAllChannels,
  addPrePersonnel,
  editPrePersonnel,
  deletePrePersonnel,
  getCheckInField,
  getQueryCount
} from "@/api/outsourcing/outsourcing";
import axios from "axios";
import qs from "qs";
import DynamicAddEmployees from "../../../staff/management/info/component/dynamicAddEmployees";
import UploadMixin from "xqjr-plugin-common/UploadOrExport/uploadMixin";
import ExportMixin from "xqjr-plugin-common/UploadOrExport/exportMixin";
const mixin2 = new ExportMixin();
const mixin = new UploadMixin();
import { uploadGeneralImg } from "@/api/file/file";
import bulkChanges from "./bulkChanges";
import { mapGetters } from "vuex";
export default {
  mixins: [mixin, mixin2],
  components: {
    DynamicAddEmployees,
    bulkChanges,
    // eslint-disable-next-line vue/no-unused-components
    Uploading: () => import("@/components/Uploading/uploading")
  },
  data() {
    const validatorPhone = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
          callback(new Error("请输入11位数字类型手机号!"));
        } else {
          callback();
        }
      }
    };
    const validatorIdCard = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
          callback(new Error("请输入正确的身份证号!"));
        } else {
          callback();
        }
      }
    };
    return {
      preStatusVarList,
      batchVal: "批量操作",
      checkInIdForm: null,
      checkInAllValue: {},
      params: {
        templateName: "checkInPeopleImportTemplate.xlsx"
      },
      url2: `/hr/api/v1/excel/template/download`,
      excelName: "预登记人员上传模板.xlsx",
      imgFile: "",
      isCloseMethod: false,
      spinning: false,
      isConnect: false,
      url: "",
      loading: false,
      validatorPhone,
      validatorIdCard,
      inductDetail: {},
      title: "添加预登记人员",
      visible: false,
      inductionVisible: false,
      channelName: null,
      dataList: [],
      Channels: [],
      columns,
      form: {},
      storyCompanyId: null,
      nameOrPhoneOrIdcard: null,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      deleteVisible: false,
      status: null,
      channelId: null,
      params2: {},
      key: "1",
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        personalPeriod: null,
        editCompanyName: null,
        ticketRecord: null,
        receivableRecord: null,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      allCount: 0,
      goInductionUrl: ""
    };
  },
  computed: {
    ...mapGetters(["isJF"]),
    options() {
      return this.$store.state.hr.companyList;
    }
  },
  created() {
    this.getAllChannelsList();
    this.getPrePersonnelList();
    this.action = `/hr/api/v1/checkInPeoples/importCheckInPeople`;
  },
  methods: {
    saveOk() {
      this.getAllChannelsList();
      this.getPrePersonnelList();
      this.onGetQueryCount();
    },
    batchHandleChange(e) {
      if (e === "状态" || e === "渠道") {
        this.$nextTick(() => {
          this.batchVal = "批量操作";
          this.$refs.select.showModal(e);
        });
      }
    },
    // 删除
    onRemove() {
      this.deleteOk();
    },
    // 点击取消
    cancelForm() {
      this.visible = false;
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message("最多只能上传一个");
        return false;
      }
      this.fileList = [...this.fileList, file];
      if (this.fileList && this.fileList.length > 0) {
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append("file", file);
        });
        this.uploading = true;

        axios({
          url: this.action,
          method: "post",
          data: formData,
          headers: this.headers
        }).then((res) => {
          this.getPrePersonnelList();
          this.reset();
          this.uploading = false;
        });
      } else {
        this.reset();
        this.handleUploadError();
      }
      return false;
    },
    exportFile() {
      this.params2 = {
        nameOrPhoneOrIdcard: this.nameOrPhoneOrIdcard ? this.nameOrPhoneOrIdcard : null,
        status: this.status ? this.status : null,
        channelId: this.channelId ? this.channelId : null,
        notSource: "花名册"
      };
      this.url = `/hr/api/v1/checkInPeoples/checkInPeopleExport`;
      this.excelName = `预登记人员详情.xlsx`;
      this.getDownload();
    },
    getDownload() {
      axios({
        url: this.url,
        params: this.params2,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: this.token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    download2() {
      const token = this.$store.state.auth.token;
      axios({
        url: this.url2,
        params: this.params,
        paramsSerializer: (param) => {
          return qs.stringify(param, { indices: false });
        },
        method: "get",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then((res) => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", this.excelName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    base64ImgtoFile(dataurl, filename = "file") {
      const arr = dataurl.split(",");
      const mime = arr[0].match(/:(.*?);/)[1];
      const suffix = mime.split("/")[1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      });
    },
    callback(key) {
      this.$set(this, "form", {});
      this.key = key;
    },
    download() {
      window.open(
        "https://public-zhixinren.oss-cn-hangzhou.aliyuncs.com/CVR-100U%E9%A9%B1%E5%8A%A8%E7%A8%8B%E5%BA%8F%E3%80%81%E8%AF%BB%E5%8D%A1%E8%BD%AF%E4%BB%B6%E4%B8%8B%E8%BD%BD.zip"
      );
    },
    cancelSyn() {
      this.isCloseMethod = false;
    },
    howShow() {
      this.isCloseMethod = true;
    },
    onSuccess(data) {
      this.spinning = false;
      var info = data.match('"errorMsg" : (.*)')[1];

      if (info === '"打开成功",') {
        this.isConnect = true;
      } else if (info === '"关闭读卡器成功",' || info === '"关闭读卡器失败",') {
        this.isConnect = false;
      } else if (info === '"读卡失败",') {
        this.$notification["error"]({
          message: "读卡失败",
          description: "请重新连接设备后重试"
        });
      } else if (info === '"读卡成功",') {
        var certType = data.match('"certType" : "(.*?)"')[1];
        if (certType === " ") {
          certType = "身份证";
        } else if (certType === "I") {
          certType = "外国人居住证";
        } else if (certType === "J") {
          certType = "港澳台居住证";
        } else {
          certType = "未知";
        }

        var partyName = data.match('"partyName" : "(.*?)"')[1]; // 名字
        var gender = data.match('"gender" : "(.*?)"')[1]; // 性别
        var nation = data.match('"nation" : "(.*?)"')[1]; // 民族
        var bornDay = data.match('"bornDay" : "(.*?)"')[1]; // 出生日期
        var certAddress = data.match('"certAddress" : "(.*?)"')[1]; // 地址
        var certNumber = data.match('"certNumber" : "(.*?)"')[1]; // 身份证号
        var certOrg = data.match('"certOrg" : "(.*?)"')[1]; // 公安局
        var effDate = data.match('"effDate" : "(.*?)"')[1]; // 有效期限 开始
        var expDate = data.match('"expDate" : "(.*?)"')[1]; // 有效期限 结束
        var identityPic = data.match('"identityPic" : "(.*?)"')[1]; // 头像
        // document.all['PhotoDisplay'].src = 'data:image/jpeg;base64,' + data.match("\"identityPic\" : \"(.*?)\"")[1];
        this.$set(this.form, "name", partyName);
        this.$set(this.form, "idcard", certNumber);
        this.$set(this.form, "nation", nation);
        this.$set(this.form, "birthday", bornDay);
        this.$set(this.form, "nativeLocation", certAddress);
        this.$set(this.form, "issuedBy", certOrg);
        this.$set(this.form, "startDate", effDate);
        this.$set(this.form, "endDate", expDate);
        this.$set(this.form, "img", "data:image/jpeg;base64," + identityPic);
        this.imgFile = this.base64ImgtoFile(this.form.img);
      } else if (info === '"无法打开读卡器",') {
        this.$notification["error"]({
          message: "未检测到读卡器",
          description: "请检查后重试"
        });
      }
    },
    connectDevice() {
      this.spinning = true;
      // eslint-disable-next-line no-new-object
      var options = new Object();
      options.type = "GET";
      // options.url = "/OpenDevice";
      if (this.isConnect) {
        options.url = "http://127.0.0.1:19196/CloseDevice" + "&" + "t=" + Math.random(); // URL后面加一个随机参数的目的是为了防止IE内核浏览器的数据缓存
      } else {
        options.url = "http://127.0.0.1:19196/OpenDevice" + "&" + "t=" + Math.random(); // URL后面加一个随机参数的目的是为了防止IE内核浏览器的数据缓存
      }

      options.timeout = 5000;
      options.onSuccess = this.onSuccess;
      this.ajax(options);
    },

    readIdCard() {
      this.spinning = true;
      // eslint-disable-next-line no-new-object
      var options = new Object();
      options.type = "GET";
      // options.url = "/OpenDevice";
      options.url = "http://127.0.0.1:19196/readcard" + "&" + "t=" + Math.random(); // URL后面加一个随机参数的目的是为了防止IE内核浏览器的数据缓存

      options.timeout = 5000;
      options.onSuccess = this.onSuccess;
      this.ajax(options);
    },
    ajax(options) {
      if (options.type == null) {
        options.type = "POST";
      }

      if (options.url == null) {
        options.url = "";
      }

      if (options.timeout == null) {
        options.timeout = 5000;
      }

      if (options.onComplate == null) {
        options.onComplate = function () {};
      }

      if (options.onError == null) {
        options.onError = function () {};
      }

      if (options.onSuccess == null) {
        options.onSuccess = function () {};
      }

      if (options.data) {
        options.data = "";
      }

      var xml;
      if (typeof XMLHttpRequest !== "undefined") {
        xml = new XMLHttpRequest();
      }

      xml.open(options.type, options.url, true);

      var timeoutLength = options.timeout;

      var requestDone = false;

      setTimeout(function () {
        requestDone = true;
      }, timeoutLength);

      xml.onreadystatechange = () => {
        if (xml.readyState === 4 && !requestDone) {
          if (this.httpSuccess(xml)) {
            options.onSuccess(this.httpData(xml));
          } else {
            options.onError();
          }

          options.onComplate();

          xml = null;
        }
      };

      xml.send();
    },

    httpSuccess(r) {
      try {
        return (
          (!r.status && location.protocol === "file:") ||
          (r.status >= 200 && r.status <= 300) ||
          r.status === 304 ||
          (navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status === "undefined")
        );
        // eslint-disable-next-line no-empty
      } catch (e) {}
      return false;
    },
    httpData(r) {
      var ct = r.getResponseHeader("responseType");
      if (ct) {
        // if(ct=="script")
        // {
        //  eval.call(window, data);
        // }
        if (ct === "xml") {
          return r.responseXML;
        }
        if (ct === "json") {
          return JSON.parse(r.responseText);
        }
      }
      return r.responseText;
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    filterOption2(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    filterOption3(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    selectCheck(e) {
      this.channelId = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getPrePersonnelList();
    },
    selectCheck2(e) {
      this.status = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getPrePersonnelList();
    },
    // 删除
    showDelete() {
      this.deleteVisible = true;
    },
    deleteOk() {
      deletePrePersonnel(this.form.id).then((res) => {
        this.$notification["success"]({
          message: "success",
          description: "删除成功"
        });
        this.pagination.current = 1;
        this.pagination.pageSize = 10;
        this.deleteVisible = false;
        this.visible = false;
        this.$set(this, "form", {});
        this.imgFile = "";
        this.url = "";
        this.getPrePersonnelList();
      });
    },
    deleteCancel() {
      this.deleteVisible = false;
    },
    // 入职
    induction(e, text) {
      this.goInductionUrl = text;
      this.inductionVisible = true;
      this.inductDetail = e;
      this.storyCompanyId = undefined;
    },
    InductOk() {
      if (this.storyCompanyId !== null && this.storyCompanyId !== undefined) {
        this.inductionVisible = false;

        this.$store.dispatch("onCompanyClick", {
          id: this.storyCompanyId
        });

        // sessionStorage.setItem("selectTreeId", this.storyCompanyId);

        const checkInId = { companyId: "site", checkInId: this.inductDetail.id };
        getCheckInField(checkInId)
          .then((res) => {
            const data = Object.assign(
              res.data.checkInPeopleVO,
              res.data.data,
              { checkInId: this.inductDetail.id },
              { additionalFieldVOList: res.data.additionalFieldVOList }
            );
            this.$router.push({
              path: this.goInductionUrl === "induction" ? "/staff/employee" : "/staff/manger",
              query: {
                outEmpDetail: JSON.stringify(data),
                EmpState: "out"
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$message.error("请选择用工单位");
      }
    },
    InductCancel() {
      this.inductionVisible = false;
    },
    selectChange(e) {
      this.form.channelId = e;
    },
    // 编辑
    edit(e) {
      this.title = e.status === 4 ? "查看" : "编辑";
      this.$nextTick(() => {
        const checkInId = { companyId: "site", checkInId: e.id };
        this.checkInIdForm = e.id;
        this.form.id = e.id;
        getCheckInField(checkInId)
          .then((res) => {
            const data = res.data.data;
            const token = this.$store.state.auth.token;
            const additionalFieldVOList = res.data.additionalFieldVOList.reduce(function (res, key) {
              res[key.fieldId] = key.content;
              return res;
            }, {});
            const data1 = Object.assign(
              {},
              additionalFieldVOList,
              res.data.checkInPeopleVO,
              {
                additionalFieldVOList: res.data.additionalFieldVOList
              },
              data
            );
            Object.keys(data1).map((z) => {
              if (typeof data1[z] === "number" && data1[z].toString().length === 1) {
                data1[z] = data1[z] + "";
              }
              if (typeof data1[z] === "string" && data1[z].indexOf("https://") !== -1) {
                data1[z] = data1[z].split(",").filter((z) => `${z}?token=${token}`);
              }
            });
            this.checkInAllValue = data1;
            this.visible = true;
          })
          .catch((err) => {
            console.log(err);
          });
        this.$set(this, "form", JSON.parse(JSON.stringify(e)));
        this.url = this.form.photo;
      });
    },
    // 获取全部通道
    getAllChannelsList() {
      getAllChannels({ isNotChannel: true }).then((res) => {
        this.Channels = res.data;
      });
    },
    getPrePersonnelList() {
      this.loading = true;
      this.onGetQueryCount();
      getPrePersonnel({
        notSource: "花名册",
        "orders[0].property": "status",
        "orders[1].property": "gmtCreate",
        "orders[0].desc": false,
        "orders[1].desc": true,
        nameOrPhoneOrIdcard: this.nameOrPhoneOrIdcard ? this.nameOrPhoneOrIdcard : null,
        status: this.status ? this.status : null,
        channelId: this.channelId ? this.channelId : null,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        isShowOtherInfo: true
      }).then((res) => {
        this.loading = false;
        this.$nextTick(() => {
          this.dataList = res.data.entities;
          this.pagination.total = res.data && res.data.entityCount;
        });
      });
    },
    // 点击确定
    handleAddOK() {
      if (!this.form.name) {
        this.$message.error("请填写姓名");
        return;
      }
      if (!this.form.idcard) {
        this.$message.error("请填写身份证号");
        return;
      }
      if (this.form.nation) {
        const nation = this.form.nation.replace(/族/g, "");
        this.$set(this.form, "nation", nation + "族");
      }

      if (this.key === "1") {
        this.$set(this.form, "type", 1);
        // 手动填写
        this.commitOK();
      } else if (this.key === "2") {
        this.$set(this.form, "type", 2);
        // 机器识别
        if (this.imgFile && this.imgFile !== "") {
          const formData = new FormData();
          formData.append("files", this.imgFile);
          uploadGeneralImg(formData)
            .then((res) => {
              this.url = res.data[0];
              this.commitOK();
            })
            .catch((err) => {
              console.log("debug log --> ", err);
            });
        } else {
          this.commitOK();
        }
      }
    },
    commitOK() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.form.channelId) {
            this.$set(this.form, "channelId", "");
            this.$set(this.form, "channelName", "");
          }
          if (this.url && this.url !== "") {
            this.$set(this.form, "photo", this.url);
          }

          if (this.title === "添加预登记人员") {
            addPrePersonnel({ ...this.form, source: "预登记" }).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "添加成功"
              });
              this.url = "";
              this.$set(this, "form", {});
              this.imgFile = "";
              // eslint-disable-next-line no-empty
              if (this.key === "2") {
              } else {
                this.visible = false;
              }

              this.getPrePersonnelList();
            });
          }
          if (this.title === "编辑") {
            editPrePersonnel(this.form).then((res) => {
              this.$notification["success"]({
                message: "success",
                description: "编辑成功"
              });
              this.url = "";
              this.$set(this, "form", {});
              this.imgFile = "";
              this.visible = false;
              this.getPrePersonnelList();
            });
          }
        } else {
          return false;
        }
      });
    },
    saveValueChange(data) {
      this.form = data;
      if (this.title === "添加预登记人员") {
        addPrePersonnel({ ...this.form, source: "预登记" }).then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "添加成功"
          });
          this.url = "";
          this.$set(this, "form", {});
          this.imgFile = "";
          // eslint-disable-next-line no-empty
          if (this.key === "2") {
          } else {
            this.visible = false;
          }

          this.getPrePersonnelList();
        });
      }
      if (this.title === "编辑") {
        this.form.id = this.checkInIdForm;
        if (this.form.addEmpFieldList.length !== 0) {
          this.form.addEmpFieldList.map((z) => {
            z.moduleCode = "checkIn";
            return z;
          });
        }
        editPrePersonnel(this.form).then((res) => {
          this.$notification["success"]({
            message: "success",
            description: "编辑成功"
          });
          this.url = "";
          this.$set(this, "form", {});
          this.imgFile = "";
          this.visible = false;
          this.getPrePersonnelList();
        });
      }
    },
    // 控制新增编辑框
    showAdd() {
      this.visible = true;
      this.title = "添加预登记人员";
      this.$nextTick(() => {
        // this.$refs.ruleForm.clearValidate();
        this.$set(this, "form", {});
      });
    },
    onClose() {
      this.visible = false;
      this.url = "";
      this.$set(this, "form", {});
      this.imgFile = "";
    },
    // 搜索框
    inputChange(e) {
      this.nameOrPhoneOrIdcard = e;
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      this.getPrePersonnelList();
    },
    // 分页器
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getPrePersonnelList();
    },
    onTodayAdd() {
      this.$router.push({
        name: "prePersonnel/todayAdd"
      });
    },
    onUpload() {
      this.$router.push({
        name: "prePersonnel/upload"
      });
    },
    async onGetQueryCount() {
      try {
        const { data } = await getQueryCount({
          date: this.moment().format("YYYY-MM-DD HH:mm:ss"),
          status: 2
        });
        this.allCount = data.allCount;
      } catch (err) {
        console.log("error log --> ", err);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.emp-title {
  margin-left: 15px;
  font-weight: 700;
  font-size: 14px;
  color: #333333;
}
.rowdalog2 {
  display: flex;
  flex-direction: row;
  width: 100%;
}
.headerBox {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  // text-align: center;
  .titleName {
    font-size: 18px;
    font-weight: 500;
    color: #252525;
    line-height: 25px;
  }
}
.detailBox {
  display: flex;
  justify-content: center;
  .detailTitle {
    height: 30px;
    width: 90px;
    font-size: 14px;
    font-weight: 400;
    color: #767885;
  }
  .detailContent {
    width: 180px;
    height: 30px;
    font-size: 14px;
    font-weight: 500;
    color: #3c3d43;
  }
}
.edit {
  color: var(--primary);
}
.body {
  padding: 0 24px;
  .title {
    font-size: 18px;
    font-weight: 400;
    color: #333333;
    padding-bottom: 24px;
  }
  .action {
    display: flex;
    justify-content: space-between;
  }
}
.statusStyle {
  text-align: center;
  width: 50px;
  height: 20px;
  border-radius: 2px;
  font-size: 11px;
  font-weight: 400;
}
</style>
